package com.sinoatma.physignsmonitor.utils;

import android.app.Activity;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * This class includes a small subset of standard GATT attributes for demonstration purposes.
 */
public class Utils {

	public static boolean isBattery(int battery) {
		if (battery > 0 && battery < 99) {
			return true;
		}
		return false;
	}

	public static String subTow(String notifyCode) {
		if (!TextUtils.isEmpty(notifyCode)) {
			return notifyCode.substring(8, 10);
		} else {
			Log.e("返回码", "--空");
			return "";
		}
	}

	private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5',
			'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

	/**
	 * 方法
	 * byte[] to hex string
	 *
	 * @param bytes
	 * @return
	 */
	public static String bytesToHexFun(byte[] bytes) {
		char[] buf = new char[bytes.length * 2];
		int index = 0;
		for (byte b : bytes) { // 利用位运算进行转换，可以看作方法一的变种
			buf[index++] = HEX_CHAR[b >>> 4 & 0xf];
			buf[index++] = HEX_CHAR[b & 0xf];
		}

		return new String(buf);
	}

	/**
	 * 将16进制字符串转换为byte[]
	 *
	 * @param str
	 * @return
	 */
	public static byte[] toBytes(String str) {
		if (str == null || str.trim().equals("")) {
			return new byte[0];
		}

		byte[] bytes = new byte[str.length() / 2];
		for (int i = 0; i < str.length() / 2; i++) {
			String subStr = str.substring(i * 2, i * 2 + 2);
			bytes[i] = (byte) Integer.parseInt(subStr, 16);
		}

		return bytes;
	}
	/**
	 * 将字符串转换为十六进制字符串，若转换后不足12位十六进制字符，则在末尾补0凑够12位
	 *
	 * @param input 要转换的普通字符串
	 * @return 转换后的十六进制字符串，长度固定为12位十六进制字符
	 */
	public static String stringToHex(String input) {
		if (input == null || input.length() < 6 || input.length() > 12) {
			throw new IllegalArgumentException("输入字符串长度不符合要求");
		}
		StringBuilder hexBuilder = new StringBuilder();
		byte[] bytes = input.getBytes();
		for (byte b : bytes) {
			String hex = Integer.toHexString(b & 0xFF).toUpperCase();
			if (hex.length() == 1) {
				hexBuilder.append("0").append(hex);
			} else {
				hexBuilder.append(hex);
			}
		}
		// 计算需要补0的数量
		int paddingZeroCount = 12 - hexBuilder.length()/2;
		for (int i = 0; i < paddingZeroCount*2; i++) {
			hexBuilder.append("0");
		}
		return hexBuilder.toString();
	}


	/**
	 * 将十六进制字符串转换为文本字符串的函数
	 *
	 * @param hexStr 十六进制字符串
	 * @return 转换后的文本字符串，如果十六进制字符串格式有误则返回空字符串
	 */
	public static String hexToText(String hexStr) {
		if (hexStr == null || hexStr.length() % 2!= 0) {
			return "";
		}
		byte[] bytes = new byte[hexStr.length() / 2];
		for (int i = 0; i < hexStr.length(); i += 2) {
			int high = Character.digit(hexStr.charAt(i), 16);
			int low = Character.digit(hexStr.charAt(i + 1), 16);
			if (high == -1 || low == -1) {
				return "";
			}
			bytes[i / 2] = (byte) ((high << 4) + low);
		}
		return new String(bytes, StandardCharsets.UTF_8);
	}
	public static byte[] hexToBytes(String hexStr) {
		int len = hexStr.length();
		hexStr = hexStr.toUpperCase();
		byte[] des;
		if (len % 2 != 0 || len == 0) {
			return null;
		} else {
			int halfLen = len / 2;
			des = new byte[halfLen];
			char[] tempChars = hexStr.toCharArray();
			for (int i = 0; i < halfLen; ++i) {
				char c1 = tempChars[i * 2];
				char c2 = tempChars[i * 2 + 1];
				int tempI = 0;
				if (c1 >= '0' && c1 <= '9') {
					tempI += ((c1 - '0') << 4);
				} else if (c1 >= 'A' && c1 <= 'F') {
					tempI += (c1 - 'A' + 10) << 4;
				} else {
					return null;
				}
				if (c2 >= '0' && c2 <= '9') {
					tempI += (c2 - '0');
				} else if (c2 >= 'A' && c2 <= 'F') {
					tempI += (c2 - 'A' + 10);
				} else {
					return null;
				}
				des[i] = (byte) tempI;
				// System.out.println(des[i]);
			}
			return des;
		}
	}

	private static HashMap<Integer, String> serviceTypes = new HashMap();

	static {
		// Sample Services.
		serviceTypes.put(BluetoothGattService.SERVICE_TYPE_PRIMARY, "PRIMARY");
		serviceTypes.put(BluetoothGattService.SERVICE_TYPE_SECONDARY, "SECONDARY");
	}

	public static String getServiceType(int type) {
		return serviceTypes.get(type);
	}


	//-------------------------------------------
	private static HashMap<Integer, String> charPermissions = new HashMap();

	static {
		charPermissions.put(0, "UNKNOW");
		charPermissions.put(BluetoothGattCharacteristic.PERMISSION_READ, "READ");
		charPermissions.put(BluetoothGattCharacteristic.PERMISSION_READ_ENCRYPTED, "READ_ENCRYPTED");
		charPermissions.put(BluetoothGattCharacteristic.PERMISSION_READ_ENCRYPTED_MITM, "READ_ENCRYPTED_MITM");
		charPermissions.put(BluetoothGattCharacteristic.PERMISSION_WRITE, "WRITE");
		charPermissions.put(BluetoothGattCharacteristic.PERMISSION_WRITE_ENCRYPTED, "WRITE_ENCRYPTED");
		charPermissions.put(BluetoothGattCharacteristic.PERMISSION_WRITE_ENCRYPTED_MITM, "WRITE_ENCRYPTED_MITM");
		charPermissions.put(BluetoothGattCharacteristic.PERMISSION_WRITE_SIGNED, "WRITE_SIGNED");
		charPermissions.put(BluetoothGattCharacteristic.PERMISSION_WRITE_SIGNED_MITM, "WRITE_SIGNED_MITM");
	}

	public static String getCharPermission(int permission) {
		return getHashMapValue(charPermissions, permission);
	}

	//-------------------------------------------
	private static HashMap<Integer, String> charProperties = new HashMap();

	static {

		charProperties.put(BluetoothGattCharacteristic.PROPERTY_BROADCAST, "BROADCAST");
		charProperties.put(BluetoothGattCharacteristic.PROPERTY_EXTENDED_PROPS, "EXTENDED_PROPS");
		charProperties.put(BluetoothGattCharacteristic.PROPERTY_INDICATE, "INDICATE");
		charProperties.put(BluetoothGattCharacteristic.PROPERTY_NOTIFY, "NOTIFY");
		charProperties.put(BluetoothGattCharacteristic.PROPERTY_READ, "READ");
		charProperties.put(BluetoothGattCharacteristic.PROPERTY_SIGNED_WRITE, "SIGNED_WRITE");
		charProperties.put(BluetoothGattCharacteristic.PROPERTY_WRITE, "WRITE");
		charProperties.put(BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE, "WRITE_NO_RESPONSE");
	}

	public static String getCharPropertie(int property) {
		return getHashMapValue(charProperties, property);
	}

	//--------------------------------------------------------------------------
	private static HashMap<Integer, String> descPermissions = new HashMap();

	static {
		descPermissions.put(0, "UNKNOW");
		descPermissions.put(BluetoothGattDescriptor.PERMISSION_READ, "READ");
		descPermissions.put(BluetoothGattDescriptor.PERMISSION_READ_ENCRYPTED, "READ_ENCRYPTED");
		descPermissions.put(BluetoothGattDescriptor.PERMISSION_READ_ENCRYPTED_MITM, "READ_ENCRYPTED_MITM");
		descPermissions.put(BluetoothGattDescriptor.PERMISSION_WRITE, "WRITE");
		descPermissions.put(BluetoothGattDescriptor.PERMISSION_WRITE_ENCRYPTED, "WRITE_ENCRYPTED");
		descPermissions.put(BluetoothGattDescriptor.PERMISSION_WRITE_ENCRYPTED_MITM, "WRITE_ENCRYPTED_MITM");
		descPermissions.put(BluetoothGattDescriptor.PERMISSION_WRITE_SIGNED, "WRITE_SIGNED");
		descPermissions.put(BluetoothGattDescriptor.PERMISSION_WRITE_SIGNED_MITM, "WRITE_SIGNED_MITM");
	}

	public static String getDescPermission(int property) {
		return getHashMapValue(descPermissions, property);
	}


	private static String getHashMapValue(HashMap<Integer, String> hashMap, int number) {
		String result = hashMap.get(number);
		if (TextUtils.isEmpty(result)) {
			List<Integer> numbers = getElement(number);
			result = "";
			for (int i = 0; i < numbers.size(); i++) {
				result += hashMap.get(numbers.get(i)) + "|";
			}
		}
		return result;
	}

	/**
	 * 位运算结果的反推函数10 -> 2 | 8;
	 */
	static private List<Integer> getElement(int number) {
		List<Integer> result = new ArrayList<Integer>();
		for (int i = 0; i < 32; i++) {
			int b = 1 << i;
			if ((number & b) > 0)
				result.add(b);
		}

		return result;
	}


	public static String bytesToHexString(byte[] src) {
		StringBuilder stringBuilder = new StringBuilder("");
		if (src == null || src.length <= 0) {
			return null;
		}
		for (int i = 0; i < src.length; i++) {
			int v = src[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		return stringBuilder.toString();
	}


	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}


	public static void restartApp(Activity activity, Class<?> homeClass) {
		Intent intent = new Intent(activity, homeClass);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
		activity.startActivity(intent);
		// 杀掉进程
		android.os.Process.killProcess(android.os.Process.myPid());
		System.exit(0);
	}

	public static String convertHexToString(String hex){
		StringBuilder sb = new StringBuilder();
//		StringBuilder temp = new StringBuilder();

		//49204c6f7665204a617661 split into two characters 49, 20, 4c...
		for( int i=0; i<hex.length()-1; i+=2 ){

			//grab the hex in pairs
			String output = hex.substring(i, (i + 2));

			//convert hex to decimal
			if (!output.equals("00")&&!output.equalsIgnoreCase("ff")) {
				int decimal = Integer.parseInt(output, 16);
				//convert the decimal to character
				sb.append((char) decimal);
//				temp.append(decimal);
			}
		}

		return sb.toString();
	}

















	/**
	 * 提供（相对）精确的除法运算，当发生除不尽的情况时，精确到 小数点以后10位，以后的数字四舍五入。
	 *
	 * @param v1
	 *            被除数
	 * @param v2
	 *            除数
	 * @return 两个参数的商
	 */
	public static String div(String v1, String v2) {
		return div(v1, v2, 2);
	}



	/**
	 * 提供（相对）精确的除法运算。当发生除不尽的情况时，由scale参数指 定精度，以后的数字四舍五入。
	 *
	 * @param v1
	 *            被除数
	 * @param v2
	 *            除数
	 * @param scale
	 *            表示表示需要精确到小数点以后几位。
	 * @return 两个参数的商
	 */
	public static String div(String v1, String v2, int scale) {
		if (scale < 0) {
			throw new IllegalArgumentException(
					"The scale must be a positive integer or zero");
		}
		BigDecimal b1 = new BigDecimal(v1);
		BigDecimal b2 = new BigDecimal(v2);

		BigDecimal result = null;
//		try {
//			result = b1.divide(b2);
//		} catch (Exception e) {
			result = b1.divide(b2, scale, 2);
//		}
		return String.valueOf(result);
	}











}
